package com.ynt.pay.user.aspect;

import com.ynt.pay.common.utils.FastJsonUtil;
import com.ynt.pay.user.utils.IpAdrressUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 使用AOP统一处理Web请求日志
 *
 * @Author: ganbo
 * @Date: 2019/10/28 17:50
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {

    /**
     * 使用AOP统一处理API请求日志
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Around("execution(public * com.ynt.pay.user.controller.*.*(..))")
//    @Around("@annotation(com.ynt.pay.annotation.Monitor)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Long startTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        String ip = IpAdrressUtil.getIpAdrress(request);
        log.info(Thread.currentThread().getId() + "请求开始----->api: [{}], ip:{} 请求! request = [{}]", uri, ip, FastJsonUtil.objectTOJsonString(joinPoint.getArgs()));
        Object ret = joinPoint.proceed();
        log.info(Thread.currentThread().getId() + "请求结束----->api [{}], ip:{} 返回! 耗时:{}毫秒 response = [{}]", uri, ip,
                System.currentTimeMillis() - startTime, FastJsonUtil.objectTOJsonString(ret));
        return ret;
    }

}
